import axios, {AxiosRequestConfig, AxiosResponse} from 'axios';
import {Modal} from '@opentiny/vue';
import locale from '@opentiny/vue-locale';
import router from '@/router';
import {getToken, clearToken} from '@/utils/auth';

export interface HttpResponse<T = unknown> {
    errMsg: string;
    code: string | number;
    data: T;
}

const {VITE_API_BASE_URL, VITE_BASE_API, VITE_MOCK_IGNORE,VITE_LOGIN_PAGE} =
import.meta.env || {};

if (VITE_API_BASE_URL) {
    axios.defaults.baseURL = VITE_API_BASE_URL;
}

const ignoreMockApiList = VITE_MOCK_IGNORE?.split(',') || [];
axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // const isProxy = ignoreMockApiList.includes(config.url);

        // if (isProxy) {
        //   config.url = config.url?.replace(VITE_BASE_API, '/api/v1');
        // }
        console.log(config.url)
        if (config.url === '/user/test/test1') {
            console.log(1)
            config.baseURL = 'http://127.0.0.1:9092'
        }
        const token = getToken();
        if (token) {
            if (!config.headers) {
                config.headers = {};
            }
            config.headers['X-Token'] = token
        }

        config.headers = {...config.headers};

        return config;
    },
    (error) => {
        // do something
        return Promise.reject(error);
    }
);
// add response interceptors
axios.interceptors.response.use(
    (response: AxiosResponse<HttpResponse>) => {
        const res = response.data;
        console.log(res)
        if (res.code !== 200) {
            if (res.code === 211) {
                console.log(211)
                Modal.message({
                    message: res.message,
                    status: 'error',
                });
                // setTimeout(function(){
                //     window.location.href= VITE_LOGIN_PAGE
                // }, 1500);
                return Promise.reject(new Error(res.message || 'Error'));
            }
            res.message &&
            Modal.message({
                message: res.message,
                status: 'error',
            });
            return Promise.reject(new Error(res.message || 'Error'));

        }
        return res

    },
    (error) => {
        const {status, data} = error.response;
        console.log(data)
        if (status === 401) {
            clearToken();
            router.replace({name: 'login'});
            Modal.message({
                message: locale.t('http.error.TokenExpire'),
                status: 'error',
            });
        } else {
            data.error &&
            Modal.message({
                // message: locale.t(`http.error.${data.errMsg}`),
                message: `${data.message}`,
                status: 'error',
            });
        }

        return Promise.reject(error);
    }
);
